package com.woniuxy.controller;

import com.woniuxy.domain.Product;
import com.woniuxy.service.IProductService;
import com.woniuxy.util.Constants;
import com.woniuxy.util.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@RefreshScope
@Slf4j
public class ProductController {
    @Autowired
    private IProductService iProductService;

    @GetMapping("/products/{id}")
    public ResultVO getProductById(@PathVariable Integer id,HttpServletRequest request) {
        Product product = iProductService.getProductById(id);
        if (product != null) {
//            try {
//                Thread.sleep(10);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
            log.error("响应端口:{}", request.getServerPort());
            return new ResultVO(Constants.OPER_SUCCESS, "查询成功", product);
        } else {
//            System.out.println(8 / 0);
            return new ResultVO(Constants.OPER_FAILURE, "没有找到商品");
        }
    }

    @GetMapping("/products/testloadbalance")
    public ResultVO testLoadBalance(HttpServletRequest request) {
        return new ResultVO(Constants.OPER_SUCCESS, "处理本次请求的product-service端口：" + request.getServerPort());
    }

    @PostMapping("/products")
    public ResultVO addProduct(@RequestBody Product product) {
        iProductService.addProduct(product);
        return new ResultVO(Constants.OPER_SUCCESS, "新增成功");
    }

    @PutMapping("/products")
    public ResultVO reduceProductStock(@RequestBody Product product) {
        iProductService.addProduct(product);
        return new ResultVO(Constants.OPER_SUCCESS, "修改成功");
    }

    @GetMapping("/products/api1/demo1")
    public String demo1() {
        return "demo1";
    }

    @GetMapping("/products/api1/demo2")
    public String demo2() {
        return "demo2";
    }

    @GetMapping("/products/api2/demo1")
    public String demo3() {
        return "demo3";
    }

    @GetMapping("/products/api2/demo2")
    public String demo4() {
        return "demo4";
    }

    @Autowired
    private ConfigurableApplicationContext applicationContext;

    @GetMapping("/testConfig")
    public String testConfig() {
        return applicationContext.getEnvironment().getProperty("config.test");
    }

    @Value("${config.test}")
    private String test;

    @GetMapping("/testConfig2")
    public String testConfig2() {
        return test;
    }
}